import socketio
import time
import requests

sio = socketio.Client(reconnection=True, reconnection_attempts=5, reconnection_delay=2)

server_url = 'http://your_server_url'


@sio.event
def connect():
    print('Connected to server')


@sio.event
def connect_error():
    print('Connection error. Reconnecting...')


@sio.event
def disconnect():
    print('Disconnected from server. Reconnecting...')


def check_server():
    try:
        r = requests.get(server_url)
        return r.status_code == 200
    except:
        return False


global connected


def connect_to_server():
    global connected
    while True:
        try:
            sio.connect(server_url)
            connected = True
            break
        except Exception as e:
            print(f"Failed to connect: {e}")
            time.sleep(2)


if __name__ == '__main__':
    connected = False
    while not connected:
        connect_to_server()
        if not check_server():
            print("Server is down, retrying...")
            time.sleep(2)

    # 在这里添加其他事件处理器和逻辑

    sio.wait()
